package leetcode;

/**
 * Created by Ghost on 2014/9/24 0024.
 */

public class Add_two_numbers {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        int c = 0;
        ListNode rstListNode = new ListNode(0);
        ListNode rstNext = rstListNode;
        ListNode l1Next = l1;
        ListNode l2Next = l2;
        while(l1Next!=null && l2Next!=null){
            int rst = l1Next.val+l2Next.val+c;
            c = rst>=10?1:0;
            rstNext.next = new ListNode(rst-c*10);
            rstNext = rstNext.next;
            l1Next = l1Next.next;
            l2Next = l2Next.next;
        }
        if(l2Next!=null){
            while(l2Next!=null){
                int rst = l2Next.val + c;
                c = rst >= 10?1:0;
                rstNext.next = new ListNode(rst-c*10);
                rstNext = rstNext.next;
                l2Next = l2Next.next;
            }
        }
        else if(l1Next!=null){
            while(l1Next!=null){
                int rst = l1Next.val + c;
                c = rst>=10?1:0;
                rstNext.next = new ListNode(rst-c*10);
                rstNext = rstNext.next;
                l1Next = l1Next.next;
            }
        }
        if(c>0)
            rstNext.next = new ListNode(c);
        return rstListNode.next;
    }
    public static void main(String[] args){
        ListNode a = new ListNode(5);

        ListNode b = new ListNode(5);

        ListNode rst = addTwoNumbers(a,b);
        while(rst != null){
            System.out.println(rst.val);
            rst = rst.next;
        }
    }
}
